const HtmlWebpackPlugin = require("html-webpack-plugin")
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin")
const Path = require("path")

module.exports = (env) => {
  const { production } = env
  const isProduce = production

  const developOptions = {
    mode: "development",
    entry: "./src/index.ts",
    plugins: [
      new HtmlWebpackPlugin({
        template: "./src/index.html"
      })
    ],
    module: {
      rules: [
        {
          test: /\.tsx?$/,
          use: "ts-loader",
          exclude: /node_modules/
        },
        {
          test: /\.(css|scss|sass)$/i,
          oneOf: [{ use: ["style-loader", "css-loader", "sass-loader"] }]
        }
      ]
    },
    optimization: { minimize: true }
  }
  const produceOptions = {
    mode: "production",
    entry: {
      index: "./src/css/index.scss",
      "index.mobile": "./src/css/index.mobile.scss"
    },
    plugins: [
      new MiniCssExtractPlugin({
        filename: "../package/lib/css/[name].css"
      })
    ],
    module: {
      rules: [
        {
          test: /\.(css|scss|sass)$/i,
          oneOf: [
            {
              include: [Path.resolve(__dirname, "./src/css/")],
              use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"]
            },
            { use: ["style-loader", "css-loader", "sass-loader"] }
          ]
        }
      ]
    },
    optimization: {
      minimize: true,
      minimizer: [new CssMinimizerPlugin()]
    }
  }

  return {
    resolve: {
      extensions: [".tsx", ".ts", ".js"]
    },
    ...(isProduce ? produceOptions : developOptions)
  }
}
